import pygame
import sys
import myplane
import enemy
import bullet
import supply
# 导入所有的pygame常量
from pygame.locals import *
from random import *
import traceback

# 初始化pygame这个包
pygame.init()
# 混音器全部模块初始化
pygame.mixer.init()
# 根据background.png的大小
bg_size = width, height = 480, 700
# 创建指定大小的窗口Surface对象
screen = pygame.display.set_mode(bg_size)
# 设置窗口标题
pygame.display.set_caption("飞机大战")
# 载入背景图片，并且图片像素格式转化
background = pygame.image.load("images/background.png").convert_alpha()
# 载入游戏背景音乐和音量
pygame.mixer.music.load("sound/game_music.ogg")
pygame.mixer.music.set_volume(0.2)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置游戏音效和音量
bullet_sound = pygame.mixer.Sound("sound/bullet.wav")
bullet_sound.set_volume(0.2)
bomb_sound = pygame.mixer.Sound("sound/use_bomb.wav")
bomb_sound.set_volume(0.2)
supply_sound = pygame.mixer.Sound("sound/supply.wav")
supply_sound.set_volume(0.2)
get_bomb_sound = pygame.mixer.Sound("sound/get_bomb.wav")
get_bomb_sound.set_volume(0.2)
get_bullet_sound = pygame.mixer.Sound("sound/get_bullet.wav")
get_bullet_sound.set_volume(0.2)
upgrade_sound = pygame.mixer.Sound("sound/upgrade.wav")
upgrade_sound.set_volume(0.2)
enemy3_fly_sound = pygame.mixer.Sound("sound/enemy3_flying.wav")
enemy3_fly_sound.set_volume(0.2)
enemy1_down_sound = pygame.mixer.Sound("sound/enemy1_down.wav")
enemy1_down_sound.set_volume(0.2)
enemy2_down_sound = pygame.mixer.Sound("sound/enemy2_down.wav")
enemy2_down_sound.set_volume(0.2)
enemy3_down_sound = pygame.mixer.Sound("sound/enemy3_down.wav")
enemy3_down_sound.set_volume(0.5)
me_down_sound = pygame.mixer.Sound("sound/me_down.wav")
me_down_sound.set_volume(0.2)


def add_small_enemies(group1, group2, num):
    for i in range(num):
        e1 = enemy.smallenemy(bg_size)
        group1.add(e1)
        group2.add(e1)


def add_mid_enemies(group1, group2, num):
    for i in range(num):
        e2 = enemy.midenemy(bg_size)
        group1.add(e2)
        group2.add(e2)


def add_big_enemies(group1, group2, num):
    for i in range(num):
        e3 = enemy.bigenemy(bg_size)
        group1.add(e3)
        group2.add(e3)


def inc_speed(target, inc):
    for each in target:
        each.speed += inc


def main():
    # loops表示播放次数，-1为不停地循环播放
    pygame.mixer.music.play(-1)
    # 实例化time模块的Clock对象
    clock = pygame.time.Clock()
    # 生成我方飞机
    me = myplane.MyPlane(bg_size)
    # 生成整个敌机精灵组
    enemies = pygame.sprite.Group()
    # 生成敌方小型飞机组
    small_enemies = pygame.sprite.Group()
    # 添加到整个敌机精灵组和小型敌机组
    add_small_enemies(small_enemies, enemies, 15)
    # 生成敌方中型飞机组
    mid_enemies = pygame.sprite.Group()
    # 添加到整个敌机精灵组和中型敌机组
    add_mid_enemies(mid_enemies, enemies, 4)
    # 生成敌方大型飞机组
    big_enemies = pygame.sprite.Group()
    # 添加到整个敌机机精灵组和大型敌机组
    add_big_enemies(big_enemies, enemies, 15)
    bullets = []
    # 生成超级子弹列表
    bullet2 = []
    bullet2_index = 0
    bullet2_num = 8
    for i in range(bullet2_num // 2):
        bullet2.append(bullet.Bullet2((me.rect.centerx - 33, me.rect.centery)))
        bullet2.append(bullet.Bullet2((me.rect.centerx + 30, me.rect.centery)))
    # 生成普通子弹列表
    bullet1 = []
    bullet1_index = 0
    bullet1_num = 4
    for i in range(bullet1_num):
        bullet1.append(bullet.Bullet1(me.rect.midtop))
    # 用于切换图片
    switch_image = True
    # 用于延迟
    delay = 100
    # 难度级别
    level = 1
    # 全屏炸弹
    bomb_image = pygame.image.load("images/bomb.png").convert_alpha()
    bomb_rect = bomb_image.get_rect()
    bomb_font = pygame.font.Font("font/font.ttf", 48)
    bomb_num = 3
    # 设置图片索引
    e1_destroy_index = 0
    e2_destroy_index = 0
    e3_destroy_index = 0
    me_destroy_index = 0
    # 30秒触发一个补给包
    bullet_supply = supply.bullet_supply(bg_size)
    bomb_supply = supply.bomb_supply(bg_size)
    # 设定自定义事件每隔30s返回一个用户自定义事件属性
    supply_time = USEREVENT
    pygame.time.set_timer(supply_time, 30 * 1000)
    # 统计得分
    score = 0
    # 超级子弹定时器
    double_bullet_time = USEREVENT + 1
    # 标志是否使用超级子弹
    is_double_bullet = False
    # 定义字体
    score_font = pygame.font.Font("font/font.ttf", 35)
    # 标志是否暂停游戏
    paused = False
    # 载入停止按钮图片
    pause_nor_image = pygame.image.load("images/pause_nor.png").convert_alpha()
    pause_pressed_image = pygame.image.load("images/pause_pressed.png").convert_alpha()
    resume_nor_image = pygame.image.load("images/resume_nor.png").convert_alpha()
    resume_pressed_image = pygame.image.load("images/resume_pressed.png").convert_alpha()
    paused_rect = pause_nor_image.get_rect()
    paused_rect.left, paused_rect.top = width - paused_rect.width - 10, 10
    paused_image = pause_nor_image
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                # 程序退出之前先退出pygame
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEBUTTONDOWN:
                if event.button == 1 and paused_rect.collidepoint(event.pos):
                    paused = not paused
                    # 暂停背景音乐和所有音乐
                    if paused:
                        pygame.time.set_timer(supply_time, 0)
                        pygame.mixer.music.pause()
                        pygame.mixer.pause()
                    else:
                        pygame.time.set_timer(supply_time, 30 * 1000)
                        pygame.mixer.music.unpause()
                        pygame.mixer.unpause()
            elif event.type == MOUSEMOTION:
                if paused_rect.collidepoint(event.pos):
                    if paused:
                        paused_image = resume_pressed_image
                    else:
                        paused_image = pause_pressed_image
                else:
                    if paused:
                        paused_image = resume_nor_image
                    else:
                        paused_image = pause_nor_image
            elif event.type == KEYDOWN:
                if event.key == K_SPACE:  # 如果按下空格则投放超级炸弹
                    if bomb_num:  # 如果还有超级炸弹，那么炸弹数-1
                        bomb_num -= 1
                        bomb_sound.play()
                        for each in enemies:
                            if each.rect.bottom > 0:
                                each.active = False
            elif event.type == supply_time:
                supply_sound.play()
                if choice([True, False]):
                    bomb_supply.reset()
                else:
                    bullet_supply.reset()
            elif event.type == double_bullet_time:
                is_double_bullet = False
                pygame.time.set_timer(double_bullet_time, 0)

        # 根据用户的得分增加难度
        if level == 1 and score > 50000:
            level = 2
            upgrade_sound.play()
            # 增加3架小型敌机和2架中型敌机和1架大型敌机
            add_small_enemies(small_enemies, enemies, 3)
            add_mid_enemies(mid_enemies, enemies, 2)
            add_big_enemies(big_enemies, enemies, 1)
            # 提升小型敌机速度
            inc_speed(small_enemies, 1)
        elif level == 2 and score > 300000:
            level = 3
            upgrade_sound.play()
            # 增加5架小型敌机和3架中型敌机和2架大型敌机
            add_small_enemies(small_enemies, enemies, 5)
            add_mid_enemies(mid_enemies, enemies, 3)
            add_big_enemies(big_enemies, enemies, 2)
            # 提升小型敌机速度
            inc_speed(small_enemies, 1)
            # 提升中型敌机速度
            inc_speed(mid_enemies, 1)
        elif level == 3 and score > 600000:
            level = 4
            upgrade_sound.play()
            # 增加5架小型敌机和3架中型敌机和2架大型敌机
            add_small_enemies(small_enemies, enemies, 5)
            add_mid_enemies(mid_enemies, enemies, 3)
            add_big_enemies(big_enemies, enemies, 2)
            # 提升小型敌机速度
            inc_speed(small_enemies, 1)
            # 提升中型敌机速度
            inc_speed(mid_enemies, 1)
        elif level == 4 and score > 1000000:
            level = 5
            upgrade_sound.play()
            # 增加5架小型敌机和3架中型敌机和2架大型敌机
            add_small_enemies(small_enemies, enemies, 5)
            add_mid_enemies(mid_enemies, enemies, 3)
            add_big_enemies(big_enemies, enemies, 2)
            # 提升小型敌机速度
            inc_speed(small_enemies, 1)
            # 提升中型敌机速度
            inc_speed(mid_enemies, 1)
        # 更新背景图片
        screen.blit(background, (0, 0))
        if not paused:
            # 检测用户的键盘操作，按下相应按键3返回True
            key_pressed = pygame.key.get_pressed()
            if key_pressed[K_w] or key_pressed[K_UP]:
                me.moveup()
            if key_pressed[K_s] or key_pressed[K_DOWN]:
                me.movedown()
            if key_pressed[K_a] or key_pressed[K_LEFT]:
                me.moveleft()
            if key_pressed[K_d] or key_pressed[K_RIGHT]:
                me.moveright()
            # 绘制全屏炸弹补给并检测是否获得
            if bomb_supply.active:
                bomb_supply.move()
                screen.blit(bomb_supply.image, bomb_supply.rect)
                # 我方飞机遇到全屏炸弹
                if pygame.sprite.collide_mask(bomb_supply, me):
                    # 播放音乐
                    get_bomb_sound.play()
                    if bomb_num < 3:
                        bomb_num += 1
                    # 全屏炸弹消失
                    bomb_supply.active = False
            # 绘制超级子弹补给并检测是否获得
            if bullet_supply.active:
                bullet_supply.move()
                screen.blit(bullet_supply.image, bullet_supply.rect)
                if pygame.sprite.collide_mask(bullet_supply, me):
                    get_bullet_sound.play()
                    is_double_bullet = True
                    pygame.time.set_timer(supply_time, 18 * 1000)
                    bullet_supply.active = False
            # 发射子弹
            if not (delay % 10):
                bullet_sound.play()
                # 将子弹的坐标初放到敌机的前面
                if is_double_bullet:
                    bullets = bullet2
                    bullets[bullet2_index].reset((me.rect.centerx - 33, me.rect.centery))
                    bullets[bullet2_index + 1].reset((me.rect.centerx + 30, me.rect.centery))
                    bullet2_index = (bullet2_index + 2) % bullet2_num
                else:
                    bullets = bullet1
                    bullets[bullet1_index].reset(me.rect.midtop)
                    # 使子弹的下标始终处于0-4间不停循环
                    bullet1_index = (bullet1_index + 1) % bullet1_num
            # 对于列表里的所有子弹
            for b in bullets:
                # 子弹为True
                if b.active:
                    # 子弹向上飞
                    b.moveup()
                    # 子弹绘制在背景
                    screen.blit(b.image, b.rect)
                    # 将所有与子弹相撞的敌机加入到组中
                    enemies_hit = pygame.sprite.spritecollide(b, enemies, False, pygame.sprite.collide_mask)
                    # 如果这个不为True
                    if enemies_hit:
                        # 使相撞的子弹消失，不再继续出现在画面中
                        b.active = False
                        # 对于所有相撞的敌机
                        for e in enemies_hit:
                            # 如果敌机中型敌机或者大型敌机
                            if e in mid_enemies or e in big_enemies:
                                # 敌机被击中
                                e.hit = True
                                # 生命值-1
                                e.energy -= 1
                                if e.energy == 0:
                                    e.active = False
                            # 如果是小型敌机
                            else:
                                e.active = False
            # 先绘制大型敌机
            for each in big_enemies:
                # 如果大型敌机存活
                if each.active:
                    each.move()
                    # 大型敌机被子弹击中
                    if each.hit:
                        # 绘制特效
                        screen.blit(each.image_hit, each.rect)
                        each.hit = False
                    else:
                        # 交换图片
                        if switch_image:
                            screen.blit(each.image1, each.rect)
                        else:
                            screen.blit(each.image2, each.rect)
                    # 绘制血槽
                    pygame.draw.line(screen, BLACK,
                                     (each.rect.left, each.rect.top - 5),
                                     (each.rect.right, each.rect.top - 5), 2)
                    # 当生命大于20%显示绿色，否则显示红色
                    energy_remain = each.energy / enemy.bigenemy.energy
                    if energy_remain > 0.2:
                        energy_color = GREEN
                    else:
                        energy_color = RED
                    pygame.draw.line(screen, energy_color,
                                     (each.rect.left, each.rect.top - 5),
                                     (each.rect.left + each.rect.width * energy_remain,
                                      each.rect.top - 5), 2)
                    # 大型敌机即将出现在画面，播放音效
                    if each.rect.bottom > -50:
                        enemy3_fly_sound.play(-1)
                # 毁灭
                else:
                    if not (delay % 3):
                        if e1_destroy_index == 0:
                            enemy3_down_sound.play()
                        screen.blit(each.destroy_images[e1_destroy_index], each.rect)
                        e1_destroy_index = (e1_destroy_index + 1) % 6
                        if e1_destroy_index == 0:
                            enemy3_fly_sound.stop()
                            score += 10000
                            each.reset()
            # 绘制中型敌机
            for each in mid_enemies:
                if each.active:
                    each.move()
                    if each.hit:
                        screen.blit(each.image_hit, each.rect)
                        each.hit = False
                    else:
                        screen.blit(each.image, each.rect)
                    # 绘制血槽
                    pygame.draw.line(screen, BLACK,
                                     (each.rect.left, each.rect.top - 5),
                                     (each.rect.right, each.rect.top - 5), 2)
                    # 当生命大于20%显示绿色，否则显示红色
                    energy_remain = each.energy / enemy.midenemy.energy
                    if energy_remain > 0.2:
                        energy_color = GREEN
                    else:
                        energy_color = RED
                    pygame.draw.line(screen, energy_color,
                                     (each.rect.left, each.rect.top - 5),
                                     (each.rect.left + each.rect.width * energy_remain,
                                      each.rect.top - 5), 2)
                else:
                    # 毁灭
                    if not (delay % 3):
                        if e2_destroy_index == 0:
                            enemy2_down_sound.play()
                        screen.blit(each.destroy_images[e2_destroy_index], each.rect)
                        e2_destroy_index = (e2_destroy_index + 1) % 4
                        if e2_destroy_index == 0:
                            score += 6000
                            each.reset()
            # 最后绘制小型敌机
            for each in small_enemies:
                if each.active:
                    each.move()
                    screen.blit(each.image, each.rect)
                else:
                    # 毁灭
                    if not (delay % 3):
                        if e3_destroy_index == 0:
                            enemy3_down_sound.play()
                        screen.blit(each.destroy_images[e3_destroy_index], each.rect)
                        e3_destroy_index = (e3_destroy_index + 1) % 4
                        if e3_destroy_index == 0:
                            score += 1000
                            each.reset()
            '''检测我方飞机是否与敌机组发生相撞，返回敌机组中碰撞的精灵，
            指定检测相撞的具体函数为pygame.sprite.collide_mask'''
            enemies_down = pygame.sprite.spritecollide(me, enemies, False, pygame.sprite.collide_mask)
            # 如果组中有精灵
            if enemies_down:
                # 我方飞机生存状态为False
                # me.active = False
                for e in enemies_down:
                    e.active = False

            # 绘制我方飞机，并且不停地切换图片
            if me.active:
                if switch_image:
                    screen.blit(me.image1, me.rect)
                else:
                    screen.blit(me.image2, me.rect)
            else:
                # 毁灭
                if not (delay % 3):
                    if me_destroy_index == 0:
                        me_down_sound.play()
                    screen.blit(me.destroy_images[me_destroy_index], me.rect)
                    me_destroy_index = (me_destroy_index + 1) % 4
                    if me_destroy_index == 0:
                        print("Game Over")
                        running = False
            # 剩余炸弹数量
            bomb_text = bomb_font.render("x %d" % bomb_num, True, WHITE)
            text_rect = bomb_text.get_rect()
            screen.blit(bomb_image, (10, height - 10 - bomb_rect.height))
            screen.blit(bomb_text, (20 + bomb_rect.width, height - 5 - text_rect.height))
        # 绘制得分
        score_text = score_font.render("Score: %s" % str(score), True, WHITE)
        screen.blit(score_text, (10, 5))
        screen.blit(paused_image, paused_rect)
        # 改变switch的值，来切换图片
        # 只有delay被5整除，才能实现图片的切换
        if not (delay % 5):
            switch_image = not switch_image
        delay -= 1
        if not delay:
            delay = 100
        # 更新整个显示的surface对象到屏幕
        pygame.display.flip()
        # 设置游戏最大帧率为60，每秒切换60张画面
        clock.tick(60)


if __name__ == "__main__":
    try:
        main()
    except SystemExit:
        pass
    except:
        # 捕获详细的异常
        traceback.print_exc()
        pygame.quit()
        input()
